package com.lwc.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lwc.bean.MaterialStock;
import com.lwc.bean.MaterialStockQuery;
import com.lwc.common.bean.PageBean;
import com.lwc.mapper.MaterialStockMapper;
import com.lwc.service.MaterialStockService;
import com.lwc.common.untils.UploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MaterialStockServiceImpl implements MaterialStockService {
    @Autowired
    MaterialStockMapper materialStockMapper;
    @Autowired
    HttpServletRequest request;
    @Override
    public PageBean query(MaterialStockQuery materialStockQuery) {
        PageHelper.startPage(materialStockQuery.getPage(),materialStockQuery.getPageSize());
        List<MaterialStock>  list=materialStockMapper.query(materialStockQuery);
        PageInfo info=new PageInfo<>(list);

        return new PageBean<>(materialStockQuery.getPage(), materialStockQuery.getPageSize(), info.getTotal(),list);
    }



    public String export() {
  List<MaterialStock>list=materialStockMapper.export();
        //然后获取服务器目录
        String root =request.getServletContext().getRealPath("/")+"/excel";
        File file=new File(root);
        if (!file.exists()){
            file.mkdirs();
        }
//生成新的文件名
        String newFileName = file.getAbsolutePath() + "/物流库存详情列表.xlsx";
        EasyExcel.write(newFileName, MaterialStock.class)
                .sheet("模板")
                .doWrite(() -> {
                    // 分页查询数据
                    return list;//根据list分批导出,及导出的数据就是list
                });
        return "/excel/物流库存详情列表.xlsx";//返回excel路径
//创建文件
    }

    @Override
    public Map queryorderBById(int id) {
        return materialStockMapper.queryorderById(id);
    }

    @Override
    public int tolead(MultipartFile file) {
        int rs;
        //先将excel上传到服务器
        UploadUtils  utils = new UploadUtils();
        String path = utils.toUpload(file,request,"excel");
        //获取服务器根目录
        String root = request.getServletContext().getRealPath("/");
        String fileName = root + path;
        List list  = new ArrayList<>();
        EasyExcel.read(fileName, MaterialStock.class,new PageReadListener<MaterialStock>(datalist->{
            System.out.println(datalist);
            for (int i = 0; i < 9; i++) {
                list.add(datalist.get(i));
            }
        })).sheet().doRead();
        rs = materialStockMapper.insertMultipartFileByExcel(list);
        return rs;
    }
}
